<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use app\common\model\xiluhouse\QAndA as QAndAModel;
use app\common\model\xiluhouse\QAndALike as QAndALikeModel;
use app\common\model\xiluhouse\QAndATags as QAndATagsModel;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * @title   买房问问 类
 * @desc    获取买房问问相关的接口
 */
class Question extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['question_tags_data', 'questions_list', 'question_detail'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    /**
     * @title  发布买房问问
     * @desc  发布买房问问
     *
     * @param string    $question           无         问题
     * @param string    $house_ids          无       关联房源
     * @param int       $broker_user_id     0         关联回答经纪人
     *
     */
    public function publish_question()
    {
        $params['question'] = $this->request->param('question/s', '');
        $params['house_ids'] = $this->request->param('house_ids/s', '');
        $params['broker_user_id'] = $this->request->param('broker_user_id/d', 0);

        if (!$params['question']) {
            $this->error('参数错误：问题必填');
        }

        $params['user_id'] = $this->auth->id;
        if ($params['user_id'] == $params['broker_user_id']) {
            $this->error('参数错误：不能自问自答');
        }
        $model = new QAndAModel();
        $res = $model->save($params);
        if (!$res) {
            $this->error('保存失败');
        }
        $task_log_model = new \app\common\model\xiluhouse\TaskLog;
        $task_log_model->addtasklog(4, $this->auth->id);
        $this->success('保存成功');
    }

    /**
     * @title  回答买房问问
     * @desc  经纪人回答买房问问
     *
     * @param int       $id               无            问题id
     * @param string    $answer           无            回答
     * @param string    $images           无            回答图片
     * @param string    $house_ids        无          关联房源
     *
     */
    public function publish_answer()
    {
        $id = $this->request->param('id/d', 0);
        $params['answer'] = $this->request->param('answer/s', '');
        $params['images'] = $this->request->param('images/s', '');
        $params['house_ids'] = $this->request->param('house_ids/s', '');

        if (!$id) {
            $this->error('参数错误：问题id必传');
        }
        if (!$params['answer']) {
            $this->error('参数错误：回答必填');
        }
        $params['broker_user_id'] = $this->auth->id;
        $params['state'] = 2;
        $model = new QAndAModel();
        $info = $model->get($id);
        if (!$info) {
            $this->error('不存在该问题');
        }
        if ($info['state'] != 1 || $info['status'] != 'normal') {
            $this->error('该问题已回复或已下架');
        }
        if ($params['broker_user_id'] == $info['user_id']) {
            $this->error('不能自问自答');
        }
        if ($info['broker_user_id'] != 0 && $params['broker_user_id'] != $info['broker_user_id']) {
            $this->error('该问题已指定经纪人回答，您没有权限回答该问题');
        }
        $res = $info->save($params);
        if (!$res) {
            $this->error('保存失败');
        }
        $this->success('保存成功');
    }

    /**
     * @title  买房问问分类（标签）
     * @desc   获取买房问问分类（标签）
     */
    public function question_tags_data()
    {
        $model = new QAndATagsModel();
        $data = $model->getDataByMap();
        $this->success('', $data);
    }

    /**
     * @title  买房问问列表
     * @desc  获取 买房问问列表
     *
     * @param string    $keyword            无      关键词搜索
     * @param int       $is_has_image       1      是否有图：1=全部，2=有
     * @param int       $tags_id            无      标签
     * @param int       $house_id            无      房源id
     * @param int       $broker_user_id            无      经纪人id
     *
     */
    public function questions_list()
    {
        $model = new QAndAModel();
        $keyword = $this->request->param('keyword/s', '');
        if ($keyword) {
            $map['question|answer'] = ['like', '%' . $keyword . '%'];
        }
        $map['state'] = 2;
        $broker_user_id = $this->request->param('broker_user_id/d', 0);
        if ($broker_user_id) {
            $map['q_and_a.broker_user_id'] = $broker_user_id;
        }
        $is_has_image = $this->request->param('is_has_image/d', 1);
        if ($is_has_image == 2) {
            $map['images'] = ['eq', 'not null'];
            $map['images'] = ['neq', ''];
        }
        $tags_id = $this->request->param('tags_id/d', '');
        if ($tags_id) {
            $map[] = ['exp', Db::raw("FIND_IN_SET(" . $tags_id . ",q_and_a_tags_ids)")];
        }
        $house_id = $this->request->param('house_id/d', '');
        if ($house_id) {
            $map[] = ['exp', Db::raw("FIND_IN_SET(" . $house_id . ",house_ids)")];
        }
        $map['q_and_a.status'] = 'normal';
        $list = $model->with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'broker'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'brokerprofile'])->where($map)->orderRaw('weigh desc,id desc')->paginate();
        $like_model = new QAndALikeModel();
        foreach ($list as $key => $value) {
            $list[$key]['is_like'] = false;
            // 判断是否点赞
            if ($this->auth && $this->auth->id) {
                $exist = $like_model->where('q_and_a_id', $value->id)->where('user_id', $this->auth->id)->find();
                $list[$key]['is_like'] = $exist ? true : false;
            }
        }
        $this->success('', $list);
    }

    /**
     * @title  买房问问详情
     * @desc  获取 买房问问详情
     *
     * @param int    $id            0      问题id
     *
     */
    public function question_detail()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误：问题id必传');
        }
        $model = new QAndAModel();
        $info = $model->with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'broker'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->find($id);
        if (!$info) {
            $this->error('不存在该问题');
        }
        if ($info['status'] != 'normal') {
            $this->error('该问题不存在');
        }
        $info->setInc('view_num');
        $info['is_like'] = false;
        // 判断是否点赞
        if ($this->auth && $this->auth->id) {
            $like_model = new QAndALikeModel();
            $exist = $like_model->where('q_and_a_id', $id)->where('user_id', $this->auth->id)->find();
            $info['is_like'] = $exist ? true : false;
        }
        $data['info'] = $info;
        // 相关楼盘
        $data['house_data'] = \app\common\model\xiluhouse\House::where('status', 'normal')->where(
            'id',
            'in',
            $info['house_ids']
        )->orderRaw('weigh desc,id desc')->select();
        foreach ($data['house_data'] as $key => &$value) {
            $value->append(['house_tag_ids_text_arr']);
        }

        $data['orther_data'] = $model->where('id', 'neq', $id)->where('status', 'normal')->where('state', 2)->orderRaw('rand()')->limit(3)->select();
        $this->success('', $data);
    }

    /**
     * @title  买房问问点赞
     * @desc  买房问问点赞
     *
     * @param int    $id            0      问题id
     *
     */
    public function like_answer()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误：问题id必传');
        }
        $model = new QAndAModel();
        $info = $model->with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'broker'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->find($id);
        if (!$info) {
            $this->error('不存在该问题');
        }
        if ($info['status'] != 'normal') {
            $this->error('该问题不存在');
        }

        $like_model = new QAndALikeModel();
        $exist = $like_model->where('q_and_a_id', $id)->where('user_id', $this->auth->id)->find();
        if ($exist) {
            $this->success('点赞成功');
        }
        // 启动事务
        Db::startTrans();
        try {
            $res = $like_model->save([
                'q_and_a_id' => $id,
                'user_id' => $this->auth->id,
            ]);
            if (!$res) {
                exception('提交失败，请稍后提交');
            }
            $res = $info->setInc('like_num');
            if (!$res) {
                exception('提交失败，请稍后提交');
            }
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('点赞成功');
    }

    /**
     * @title  经纪人或用户的买房问问列表
     * @desc  获取买房问问列表
     *
     * @param string    $keyword            无      关键词搜索
     * @param int       $state              0      回复状态:1=未回复,2=已回复
     * @param int       $type               1      经纪人的问题或用户提的问题:1=经纪人回答的问题,2=用户提出的问题
     *
     */
    public function my_questions_list()
    {
        $model = new QAndAModel();
        $keyword = $this->request->param('keyword/s', '');
        if ($keyword) {
            $map['question|answer'] = ['like', '%' . $keyword . '%'];
        }
        $type = $this->request->param('type/d', 1);
        if ($type == 1) {
            $map['q_and_a.broker_user_id'] = ['in', '0,' . $this->auth->id];
        } else {
            $map['q_and_a.user_id'] = ['in', '0,' . $this->auth->id];
        }

        if ($this->request->param('state/d', 0)) {
            $map['q_and_a.state'] = $this->request->param('state/d', 0);
        }

        $map['q_and_a.status'] = 'normal';
        $list = $model->with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'broker'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->where($map)->orderRaw('weigh desc,id desc')->paginate();
        $like_model = new QAndALikeModel();
        foreach ($list as $key => $value) {
            $list[$key]['is_like'] = false;
            // 判断是否点赞
            if ($this->auth && $this->auth->id) {
                $exist = $like_model->where('q_and_a_id', $value->id)->where('user_id', $this->auth->id)->find();
                $list[$key]['is_like'] = $exist ? true : false;
            }
        }
        $this->success('', $list);
    }
}
